<?php

namespace App\Models;

use App\Http\Controllers\PdfController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 线上大赛作品模型
 * Class ArticleModel
 * @package app\common\model
 */
class ContestActivityWorks extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'contest_activity_works';


    /*关联打卡信息*/
    public function conContestActivity()
    {
        return $this->hasOne(ContestActivity::class, 'id', 'con_id');
    }

    /**
     * 关联作品类型
     */
    public function conType()
    {
        return $this->hasOne(ContestActivityType::class, 'id', 'type_id');
    }

    /**
     * 获取总投票量
     * @param con_id 大赛id
     */
    public function getTotalVoteNumber($con_id)
    {
        return $this->where(function ($query) use ($con_id) {
            if ($con_id) {
                $query->where('con_id', $con_id);
            }
        })->where('status', 1)->sum('vote_num');
    }


    /**
     * 获取作品编号
     * @param  letter 作品编号
     */
    public function getSerialNumber($letter)
    {
        for ($i = 1; $i < 10; $i++) {
            $serial_number = $letter . get_rnd_number(8);

            $is_exists = $this->where('serial_number', $serial_number)->first();

            if (!$is_exists) {
                return $serial_number;
            }
            continue;
        }

        throw new \Exception('条形码获取有误，请联系管理员处理'); //获取10次都获取不到，就不在获取
    }


    /**
     * 获取未查看个数
     */
    public function getUnLookNumber($con_id)
    {
        return $this->where('con_id', $con_id)->where('is_look', 2)->count();
    }

    /**
     * 获取未审核个数
     */
    public function getUnCheckNumber($con_id)
    {
        return $this->where('con_id', $con_id)->where('status', 3)->count();
    }


    /**
     * 获取参与人数
     */
    public function getTakeNumber($con_id)
    {
        $res =  $this->where(function ($query) use ($con_id) {
            if ($con_id) {
                $query->where('con_id', $con_id);
            }
        })->whereIn('status', [1, 2, 3])->groupBy('user_id')->get()->toArray(); //分组后调用 聚合函数数据不正常，因为分组后，数据是按照分组返回，调用 count，只会返回一条数据

        return count($res);
    }
    /**
     * 获取作品数量
     */
    public function getWorksNumber($con_id)
    {
        return $this->where(function ($query) use ($con_id) {
            if ($con_id) {
                $query->where('con_id', $con_id);
            }
        })->whereIn('status', [1, 2, 3])->count();
    }

    /**
     * 判断某个活动是否有人报名
     */
    public function actIsApply($id)
    {
        $apply_status = $this->where('con_id', $id)->whereIn('status', [1, 3])->first();
        return $apply_status ? true : false;
    }



    /**
     * 判断是否有人投票
     */
    public function actIsVote($id)
    {
        $vote_num = $this->where('con_id', $id)->sum('vote_num');
        return $vote_num ? true : false;
    }

    /**
     * 参赛作品列表
     * @param con_id id
     * @param unit_id 大赛单位id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param type_id int 类型id
     * @param user_id int 用户id
     * @param sort int 排序方式  1 时间排序（默认）  2 投票排序
     * @param status int 状态  1.已通过   2.未通过   3.未审核(默认)  4.已撤销， 5已删除 6.已违规  数组形式
     * @param keywords string 搜索关键词(名称)
     * @param except_ids string 需要排除的id ，多个逗号链接
     * @param start_time datetime 创建时间范围搜索(开始) 
     * @param end_time datetime 创建时间范围搜索(结束) 
     */
    public function lists($con_id, $unit_id, $user_id = null, $type_id = null, $keywords = null, $status = ['1'], $except_ids = '', $start_time = null, $end_time = null, $sort = 'id DESC', $limit = null)
    {
        if (empty($field)) {
            $field = [
                'id', 'username', 'tel', 'id_card', 'unit_id', 'type_id', 'user_id', 'serial_number', 'cover', 'width', 'height', 'title', 'browse_num',
                'vote_num', 'status', 'create_time', 'is_look', 'is_violate', 'violate_reason', 'violate_time', 'content', 'voice', 'video', 'img'
            ];
        }
        $res = $this->select($field)
            ->where(function ($query) use ($user_id, $type_id, $status, $except_ids, $start_time, $end_time, $unit_id) {
                if ($status) {
                    $query->whereIn('status', $status);
                }
                if ($unit_id) {
                    $query->where('unit_id', $unit_id);
                }
                if ($user_id) {
                    $query->where('user_id', $user_id);
                }
                if ($type_id) {
                    $query->where('type_id', $type_id);
                }
                if ($except_ids) {
                    $except_ids = explode(',', $except_ids);
                    $query->whereNotIn('id', $except_ids);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->orWhere('serial_number', 'like', '%' . $keywords . '%')->orWhere('title', 'like', '%' . $keywords . '%');
                }
            })
            ->where('con_id', $con_id)
            ->where('status', '<>', 5)
            ->orderByRaw($sort)
            ->paginate($limit)
            ->toArray();

        //   dd(DB::getQueryLog());
        return $res;
    }

    /**
     * 获取作品详细
     * 
     */
    public function detail($id, $field = [])
    {
        if (empty($field)) {
            $field = [
                'id', 'unit_id', 'con_id', 'user_id', 'serial_number', 'username', 'tel', 'id_card', 'unit', 'wechat_number',
                'adviser', 'adviser_tel', 'reader_id', 'title', 'type_id', 'img', 'content', 'voice', 'voice_name', 'video', 'video_name',
                'intro', 'cover', 'width', 'height', 'browse_num', 'vote_num', 'status', 'reason', 'create_time', 'change_time',
                'is_violate', 'violate_reason', 'violate_time'
            ];
        }
        $res = $this->select($field)
            ->with(['conType' => function ($query) {
                $query->select('id', 'type_name', 'limit_num', 'letter', 'node');
            }])
            ->where('id', $id)
            ->first();
        return $res;
    }


    /**
     * 获取下一个未审核的作品
     */
    public function getNextUnchecked($con_id, $works_id, $unit_id, $type_id, $keywords, $start_time, $end_time, $sort)
    {
        $res = $this->select('id', 'title')
            ->where(function ($query) use ($unit_id, $type_id, $start_time, $end_time) {
                if ($unit_id) {
                    $query->where('unit_id', $unit_id);
                }
                if ($type_id) {
                    $query->where('type_id', $type_id);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('create_time', [$start_time, $end_time]);
                }
            })->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->orWhere('serial_number', 'like', '%' . $keywords . '%')
                        ->orWhere('title', 'like', '%' . $keywords . '%');
                }
            })
            ->where('con_id', $con_id)
            ->where('status', 3)
            ->where('id', '<', $works_id)
            ->orderByRaw($sort)
            ->first();

        return $res;
    }


    /**
     * 计算某个类型，某个用户上传的作品数量，超过限制，不允许在继续上传
     * @param user_id 用户id
     * @param type_id 类型id
     */
    public function getUserWorksNumberByTypeId($con_id, $user_id, $type_id)
    {
        return $this->where('con_id', $con_id)
            ->where('user_id', $user_id)
            ->where('type_id', $type_id)
            ->whereIn('status', [1, 2, 3, 4])
            ->count();
    }

    /**
     * 处理数据数据
     */
    public function disData($data, $pdf_title)
    {
        $path_arr = [];
        $pdfObj = new PdfController();
        //保存文字转换为PDF格式
        if ($data['content']) {
            $pdf_path = $pdfObj->setPdf(
                $pdf_title,
                ['<h2 style="text-align: center">' . $data['title'] . '</h1><div>' . $data['content'] . '</div>'],
                null,
                $data['serial_number']
            );
            $path_arr['pdf_path'] = $pdf_path;
            $path_arr['pdf_name'] = $data['serial_number'] . '.pdf';
        } else {
            $path_arr['pdf_path'] = null;
            $path_arr['pdf_name'] = null;
        }
        if ($data['voice']) {
            $path_arr['voice_path'] = $data['voice'];
            $voice_name = explode('.', $data['voice']);
            $path_arr['voice_name'] = $data['serial_number'] . '.' . end($voice_name);
        } else {
            $path_arr['voice_path'] = null;
            $path_arr['voice_name'] = null;
        }
        if ($data['video']) {
            $path_arr['video_path'] = $data['video'];
            $video_name = explode('.', $data['video']);
            $path_arr['video_name'] = $data['serial_number'] . '.' . end($video_name);
        } else {
            $path_arr['video_path'] = null;
            $path_arr['video_name'] = null;
        }
        if ($data['img']) {
            $path_arr['file_path'] = $data['img'];
            $img_name = explode('.', $data['img']);
            $path_arr['file_name'] = $data['serial_number'] . '.' . end($img_name);
        } else {
            $path_arr['file_path'] = null;
            $path_arr['file_name'] = null;
        }
        return $path_arr;
    }
}
